<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户控制器
 * @author Calvin
 * @modified:2016/02/24
 */
require(APPPATH.'libraries/Web_Controller.php');
class User_policies extends Web_Controller{
    private $uid = null;  //用户信息

	public function __construct() {
		parent::__construct();

		$services = array(
			'user_policies_service',
			'user_files_service',
			'login_service'
		);
		$this->load->service($services);
		$this->uid = $this->login_service->get_user_info();
	}

	/**
     * 获取文件信息和策略
     * @return bool|string
     * update 4.23 15:33
     */
	public function index_get() {
		$uuid = $this->input->get("file_id");
		$type = (int)$this->input->get("type");//0或无文件还是1文件夹

        //不存在uuid
		if (! $uuid){
            $this->common_response(1003);
            //return Common::prf_json(FALSE,NULL,NULL,NULL,TRUE,"file_id is null");
        }
        //取得文件信息和策略
		$file = $this->user_policies_service->get_policy($this->uid['id'], $type, $uuid);
		if(! $file)
        {
            if($type==1)
            {
                $this->common_response(7100);
            }
            else
            {
                $this->common_response(7001);
            }
        }
        //return Common::prf_json(FALSE,NULL,NULL,NULL,TRUE,"file is null");

        //是否计算文件夹个数
        $isCountTotal = (int)$this->input->get("isCount");

        //文件夹的大小为0
		if ($type == 1) $file['size'] = 0;
        //提出策略
        $file_policies = json_decode($file['data'], TRUE);
		$retArr = array(
            "f_id"=>$file['id'],
            "f_name"=>$file['name'],
            "f_size"=>$file['size'],
            "f_dec"=>$file['description']
        );

        //如果个数为1
		if ($isCountTotal == 1){
			$retArr['f_type'] = 0;
			$retArr['f_count'] = 0;

            //如果是文件夹,统计文件数量
			if ($type == 1) {
				$file_count = $this->user_files_service->get_folder_file_count($this->uid['id'], $file['id']);

				$retArr['f_type'] = 1;
				$retArr['f_count'] = $file_count;
			}
		}

		$isOpen = $file['access_denied'] == 0 ? TRUE : FALSE;
		$retArr['isOpen'] = $isOpen;
		$retArr["time_type"] = 1;

        //如果没有策略
		if (NULL === $file_policies) {
            $retArr['is_new'] = TRUE;
            $retArr['life_span'] = NULL;
            $retArr['open_counter'] = NULL;
            $retArr['delete_after_expired'] = NULL;

            $this->common_response(0,'',array("data"=>$retArr));
           // return Common::prf_json(TRUE, $retArr);
        }

		foreach ($file_policies as  $index => $file_policy){
            //存活时间
			if ($file_policy['des'] == 'life_span') {
                //如果时间值不为0则转换成具体时间格式
				if($file_policy['value_set'] != 0){
					$data = date('Y-m-d H:i:s',$file_policy['value_set']);
					$retArr["time_type"] = 2;

				}else{ //时间为0
                    $data = 0;
					$retArr["time_type"] = 1;
				}
				$retArr[$file_policy['des']] = $data;

			}else if($file_policy['des'] == 'read_pwd') {  //密码
				$retArr['f_pwd'] = $file_policy['value_set'];

			}else{ //其它参数
				$retArr[$file_policy['des']] =$file_policy['value_set'];
			}
		}
        $this->common_response(0,'',array("data"=>$retArr));
        //return Common::prf_json(TRUE, $retArr);
	}

	/**
	 * 即时收回状态修改
	 */
    public function check_access_denied_put() {
        $files = $this->put("files",TRUE);
        $folders = $this->put("folders",TRUE);
        $children = $this->put("children",TRUE);
        if((empty($files) && empty($folders)) ||(!empty($files) && !is_array($files)) || (!empty($folders) && !is_array($folders)))
        {
            return $this->common_response(1003);
        }
        $children = empty($children)?FALSE:TRUE;
        $data = $this->user_policies_service->get_data_access_denied($this->uid['id'], $files,$folders,1,$children);
        return $this->common_response(0, $data);
    }

    /**
     * 接收表单提交的时间，并转换为时间戳
     * @return int
     */
    private function get_expired_time() {
        $is_expired_time = $this->put("is_expired_time");
        $is_expired_time2 = $this->put("is_expired_time2");
        $is_expired_time_custom = $this->put("is_expired_time_custom");
        $expired_time = 0;
        //common::prf_json(FALSE,NULL,NULL,time(),TRUE,$is_expired_time2."//".$is_expired_time_custom);

        //具体时间
        if($is_expired_time == "on"){
            //1:时间段 2：具体时间
            /*$time_type = $this->input->post("time_type",TRUE);
            if($time_type == 1){
                $time_slot = $this->input->post("time_slot",TRUE);
                $specific = $this->common->slotToSpecific($time_slot);
                $expired_time = $this->common->minuteRound(date("Y-m-d H:i")) + $specific;
            }else{
                $datetime = $this->input->post("datetimepicker",TRUE);
                $expired_time = strtotime($datetime);
            }*/
            $datetime = $this->put("datetimepicker");
            $expired_time = strtotime($datetime);
            //过期时间不能小于当前时间
            if ($expired_time < time())  $expired_time=time();

        } else if ($is_expired_time2 == "on" && $is_expired_time_custom =="off") {  //按天/时取时间
            $time_slot = $this->put("time_slot");
            $specific = $this->common->slotToSpecific($time_slot);
            $expired_time = time() + $specific;

        } else if($is_expired_time_custom=="on") { // 自定义时间转换成时间戳
            $specific = 0;
            $time_slot_h = (int)$this->put("time_slot_h");
            $time_slot_i = (int)$this->put("time_slot_i");
            $time_slot_s = (int)$this->put("time_slot_s");
            $specific += $time_slot_h * 3600;
            $specific += $time_slot_i * 60;
            $specific += $time_slot_s;
            $expired_time = time() + $specific;
        }

        return $expired_time;
    }

    /**
     * 取得提交的策略信息
     * @return array
     */
    public function get_submits() {
        $is_only_one = $this->put("is_only_one",TRUE);
        $is_auto_del = $this->put("is_auto_del",TRUE);

        //设置仅查阅一次
        $is_only_one_value = 0;
        if ($is_only_one == "on")  $is_only_one_value = 1;
        //设置过期时间
        $expired_time = $this->get_expired_time();
        //设置自动销毁
        $is_auto_del_value = 0;
        if ($is_auto_del == "on")  $is_auto_del_value = 1;
        //设置查阅密码
        $is_read_pwd = $this->put("is_read_pwd");
        $pwd_value = '';
        if($is_read_pwd == "on"){
            $pwd_value = trim($this->put("read_pwd", TRUE));
        }

        //新策略
        $sub_policies = array(
            array('des' => 'open_counter', 'value_set' => $is_only_one_value),
            array('des' => 'life_span', 'value_set' => $expired_time),
            array('des' => 'delete_after_expired', 'value_set' => $is_auto_del_value),
            array('des' => 'read_pwd', 'value_set' => $pwd_value)
        );
        return $sub_policies;
    }

    /**
     * 单文件添加策略
     * @return string
     */
	public function update_put(){
        $uuid = (int)$this->put("f_id",TRUE); //文件id
        $type = (int)$this->put("type",TRUE ); //0文件还是1文件夹

        if (! $uuid)
            return $this->common_response(1003);

        $file = $this->user_policies_service->get_policy($this->uid['id'], $type, $uuid);
        //是否存在文件
        if (! $file)
            return $this->common_response(1003);

        //获取提交的策略信息
        $sub_policies = $this->get_submits();

        //如果类型为文件
        if ($type == 0) {
            //文件禁用
            if ($file['access_denied'] == 1) {
                $f = array(
                    'file_ids' => array($file['id'])
                );
                return $this->common_response(10001);
            }

            $file['uid'] = $this->uid['id'];
            //$this->add_policy($file, 1, $sub_policies);
            $this->user_policies_service->add_policies($file, 1, $sub_policies);
        }

        //文件夹
        if ($type == 1) {
            //是否只应用于目录下的文件及本目录
            $children = FALSE;
            //子目录所有的文件列表
            $file_list = $this->user_policies_service->get_children($this->uid['id'], $file['id'], 1, $children);

            //是否存在禁止访问的目录或文件
            $ac = FALSE;
            //禁止的目录及文件列表
            $denied_ids = array();
            //文件夹列表
            $f_folders = array();


            //只应用于当前目录下的文件
            if (! $children) {
                //如果文件夹禁止访问
                if ($file['access_denied'] == 1) {
                    $ac = TRUE;
                    $denied_ids['folder_ids'][] = $file['id'];
                }
                $file['uid'] = $this->uid['id'];
                //文件夹
                $f_folders[] = $file;

            } else {
                //取子目录列表
                $folder_list = $this->user_policies_service->get_children($this->uid['id'], $file['id'], 2, TRUE);
                //子目录遍历
                foreach ($folder_list as $k => $v) {
                    //如果当前文件是不可访问,且之前未曾有不可访问的
                    if ($v['access_denied'] == 1) {
                        if (!$ac) $ac = TRUE; //如果ac本来是false则true
                        $denied_ids['folder_ids'][] = $v['id'];
                    }

                    $v['uid'] = $this->uid['id'];
                    $f_folders[] = $v;
                }
            }

            //文件列表
            $f_files = array();
           //遍历文件并添加文件策略
            foreach ($file_list as $k => $v) {
                //如果当前文件是禁止访问
                if ($v['access_denied'] == 1) {
                    if (!$ac) $ac = TRUE; //如果ac本来是false则true
                    $denied_ids['file_ids'][] = $v['id'];
                }
                $v['uid'] = $this->uid['id'];
                $f_files[] = $v;
            }

            //如果有一个文件或文件夹access denied
            if ($ac) return $this->common_response(10001);

            //为文件添加策略
            foreach ($f_files as $v) {
                //$this->add_policy($v, 1, $sub_policies);
                $this->user_policies_service->add_policies($v, 1, $sub_policies);
            }

            //为文件夹添加策略
            foreach ($f_folders as $v) {
                //$this->add_policy($v, 2, $sub_policies);
                $this->user_policies_service->add_policies($v, 2, $sub_policies);
            }

        //文件
        }

        $retArr = array("f_id"=>$uuid);
        return $this->common_response(0,'',$retArr);
	}


	/**
     * 批量修改文件的策略
     * @return string
     */
    public function updateBatch_put() {
        //文件uuids集合
        $file_uuids = $this->put("file_uuids");
        //文件夹uuids集合
        $folder_uuids = $this->put("folder_uuids",TRUE);

        if (empty($file_uuids) && empty($folder_uuids))
            return $this->common_response(1003);

        $children = FALSE;
        $data = $this->user_policies_service->get_data_info($this->uid['id'], $file_uuids, $folder_uuids, $children);

        $ac = FALSE;  //是否存在禁止文件/文件夹开关
        $result = array();
        $denied_ids = array();

        foreach ($data as $keys => $values) {
            foreach ($values as $key => $value) {
                if ($value['access_denied'] == 1) {
                    if (!$ac) $ac = TRUE; //如果ac本来是false则true
                    $denied_ids[$keys][] = $value['id'];
                }
                $value['uid'] = $this->uid['id'];
                $result[$keys][] = $value;
            }
        }

        if ($ac) return $this->common_response(10001);

        $sub_policies = $this->get_submits();
        if (isset($result['files'])) {
            foreach ($result['files'] as $v) {
                //$this->add_policy($v, 1, $sub_policies);
                $this->user_policies_service->add_policies($v, 1, $sub_policies);
            }
        }
        if (isset($result['folders'])) {
            foreach ($result['folders'] as $v) {
                //$this->add_policy($v, 2, $sub_policies);
                $this->user_policies_service->add_policies($v, 2, $sub_policies);
            }
        }

        return $this->common_response(0);
    }

}